//
//  MTClubSendGiftCell.swift
//  MT
//
//  Created by ooops on 2020/5/10.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import Foundation
import Eureka
import MTCategory

public final class MTClubGiftDataRow: MTClubSendGiftRow, RowType {
    required public init(tag: String?) {
        super.init(tag: tag)
    }
}

open class MTClubSendGiftRow: MTClubSendGiftCellRow {
    required public init(tag: String?) {
        super.init(tag: tag)
        dateFormatter = DateFormatter()
        dateFormatter?.timeStyle = .none
        dateFormatter?.dateStyle = .medium
        dateFormatter?.locale = Locale.current
    }
}

public protocol MTClubSendGiftCellProtocol: class {
    var minimumDate: Date? { get set }
    var maximumDate: Date? { get set }
    var minuteInterval: Int? { get set }
}

open class MTClubSendGiftCell: Cell<Date>, CellType {

    public var datePicker: UIDatePicker

    public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        datePicker = UIDatePicker()
        datePicker.locale = Locale(identifier: "zh_CN")
        datePicker.datePickerMode = .time
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    required public init?(coder aDecoder: NSCoder) {
        datePicker = UIDatePicker()
        datePicker.locale = Locale(identifier: "zh_CN")
        datePicker.datePickerMode = .time
        super.init(coder: aDecoder)
    }

    /// 显示模式
    lazy var tipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "名称"
        l.textAlignment = .right
        l.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return l
    }()
    
    lazy var contentLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        l.numberOfLines = 0
        l.lineBreakMode = .byCharWrapping
        l.textAlignment = .right
        return l
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        v.isHidden = true
        return v
    }()
    
    lazy var customAccessoryView: UIImageView = {
            let imageV = UIImageView(image: UIImage(named: "icon_right_gary"))
    //        imageV.isHidden = true
//            imageV.backgroundColor = .white
            return imageV
        }()
    
    public var tipString: String? = nil
    public var contentString: String? = nil
    /// 输入框提示文字
    public var placeholder: String? {
        didSet {
            if placeholder != nil {
                let attribute: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : PingFangSCRegularFont(12),
                                                                 NSAttributedString.Key.foregroundColor : UIColor(hex: 0x5d5d5d)];
                contentLabel.attributedText = NSAttributedString(string: placeholder!, attributes: attribute)
            }
        }
    }
    
    public var isHiddenAccessory: Bool = true {
        didSet {
            customAccessoryView.isHidden = isHiddenAccessory
        }
    }
    
    public var accessoryImage: String? {
        didSet {
            if accessoryImage != nil {
                customAccessoryView.image = UIImage(named: accessoryImage!)
            } else {
                customAccessoryView.image = nil
            }
        }
    }
    
    private var isHiddenLineView: Bool = true {
        didSet {
            lineView.isHidden = isHiddenLineView
        }
    }
    
    public var isEditMode: Bool = false {
        didSet {
            lineView.isHidden = !isEditMode
            isHiddenAccessory = !isEditMode
        }
    }
    
    open override func setup() {
        super.setup()
        backgroundColor = UIColor.theme.background
        selectionStyle = .none
        textLabel?.isHidden = true
        detailTextLabel?.isHidden = true
        editingAccessoryType =  .none
        
        contentView.addSubview(tipLabel)
        contentView.addSubview(contentLabel)
        contentView.addSubview(lineView)
        contentView.addSubview(customAccessoryView)
        
        //datePicker.datePickerMode = datePickerMode()
        datePicker.addTarget(self, action: #selector(MTClubSendGiftCell.datePickerValueChanged(_:)), for: .valueChanged)
        
        makeConstraint()
    }
    
    private func makeConstraint() {
        lineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(0.5)
            make.bottom.equalToSuperview()
        }
        
        tipLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.width.greaterThanOrEqualTo(30)
        }
        
        contentLabel.snp.makeConstraints { (make) in
            make.right.equalTo(customAccessoryView.snp.left).offset(-8)
            make.left.equalTo(tipLabel.snp.right).offset(14)
            make.centerY.equalTo(tipLabel)
        }

        customAccessoryView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-8)
            make.centerY.equalTo(tipLabel)
            make.width.height.equalTo(15)
        }
    }

    deinit {
        datePicker.removeTarget(self, action: nil, for: .allEvents)
    }

    open override func update() {
        super.update()
        tipLabel.text = tipString
        
        datePicker.setDate(row.value ?? Date(), animated: row is CountDownPickerRow)
        datePicker.minimumDate = (row as? MTClubDetailDateCellProtocol)?.minimumDate
        datePicker.maximumDate = (row as? MTClubDetailDateCellProtocol)?.maximumDate
        if let minuteIntervalValue = (row as? MTClubDetailDateCellProtocol)?.minuteInterval {
            datePicker.minuteInterval = minuteIntervalValue
        }
        
        if row.value != nil {
            contentLabel.text = row.displayValueFor?(row.value)
        }
    }

    open override func didSelect() {
        super.didSelect()
        row.deselect()
    }

    override open var inputView: UIView? {
        if let v = row.value {
            datePicker.setDate(v, animated:row is CountDownRow)
        }
        return datePicker
    }

    @objc func datePickerValueChanged(_ sender: UIDatePicker) {
        row.value = sender.date
        contentLabel.text = row.displayValueFor?(row.value)
    }

    private func datePickerMode() -> UIDatePicker.Mode {
        switch row {
        case is DateRow:
            return .date
        case is TimeRow:
            return .time
        case is DateTimeRow:
            return .dateAndTime
        case is CountDownRow:
            return .countDownTimer
        default:
            return .date
        }
    }

    open override func cellCanBecomeFirstResponder() -> Bool {
        return canBecomeFirstResponder
    }

    override open var canBecomeFirstResponder: Bool {
        return isEditMode
    }
}

open class MTClubSendGiftCellRow: Row<MTClubSendGiftCell>, MTClubSendGiftCellProtocol, NoValueDisplayTextConformance {

    /// The minimum value for this row's UIDatePicker
    open var minimumDate: Date?

    /// The maximum value for this row's UIDatePicker
    open var maximumDate: Date?

    /// The interval between options for this row's UIDatePicker
    open var minuteInterval: Int?

    /// The formatter for the date picked by the user
    open var dateFormatter: DateFormatter?

    open var noValueDisplayText: String? = nil

    required public init(tag: String?) {
        super.init(tag: tag)
        displayValueFor = { [unowned self] value in
            guard let val = value, let formatter = self.dateFormatter else { return nil }
            return formatter.string(from: val)
        }
    }
}
